import { createStore } from 'vuex'

export default createStore({
  state: {
    shopCar:JSON.parse(localStorage.getItem('cart'))||[],//存放购物车数据
    checkAll:localStorage.getItem('all')|| false,//全选按钮的默认状态
    
  },
  getters: {
    getPrice(state){
        let total = 0
        state.shopCar.forEach(item=>{
            if(item.status){
                total+=item.num*item.salePrice
            }
        })
        // 计算属性的return
        return total
    }
  },
  mutations: {
    addCart(state,obj){
      let items = state.shopCar.find(item=>item.id == obj.id)
      console.log(items);
      if(items){
        // 相同商品加入   num++
        items.num++

      }else{
        // 第一次加入  给obj里面添加一个num字段
        // 给obj在加一个status字段，表示是否选中
        obj.num = 1
        obj.status = false
        state.shopCar.push(obj)
      }
     localStorage.setItem('cart',JSON.stringify(state.shopCar))
    },
    // 全选
    selectAll(state,all){
        state.shopCar.forEach(item=>{
            item.status = all
        })
        localStorage.setItem('cart',JSON.stringify(state.shopCar))
       
    },
    // 单选框的事件
    checks(state){
        // state.checkAll是全选按钮的状态 把every返回值赋值给全选按钮状态
       state.checkAll = state.shopCar.every(item=>item.status)
        // 存储全选按钮的状态
       localStorage.setItem('all',state.checkAll)
    },
    del(state,index){
        state.shopCar.splice(index,1)
        localStorage.setItem('cart',JSON.stringify(state.shopCar))

    },
    kong(state){
        localStorage.setItem('cart',JSON.stringify(state.shopCar))
    }
  },
  actions: {
    
  },
  modules: {
     
  }
})
